<?php
namespace app\index\controller;
//use think\Validate;
use app\common\controller\Api;
use think\Validate;
use app\index\model\AdminUser as Admin;
use think\facade\Session;

class AdminUser extends Api
{
    public $keeptime = 86400;
    public $id = 0;
    public function index()
    {
        return 'hello';
    }

    public function login(){
        $username = $this->request->param('username');
        $password = $this->request->param('password');
        $rule = [
            'username'  => 'require|length:4,16',
            'password'  => 'require|length:6,16'
        ];
        $data = [
            'username'  => $username,
            'password'  => $password
        ];
        $validate = new Validate($rule, [], ['username' => '用户名', 'password' => '密码']);
        $result = $validate->check($data);
        if (!$result) {
            $this->error($validate->getError(), [], 2);
        }
        $admin = Admin::where('username', $username)->find();
        if (!$admin) {
            $this->error('用户名或密码错误', [], 4);
            return false;
        }
        if ($admin->password != md5(md5($password))) {
            $this->error('用户名或密码错误', [], 4);
            return false;
        }
        $this->id = $admin['id'];
        $admin->last_login_time = date("Y-m-d H:i:s");
        $admin->save();
        Session::set("admin", $admin->toArray());
        $this->keeplogin($this->keeptime);
        $this->success('登陆成功', ['keeptime'=>$this->keeptime-60], 1);
        return true;
    }

    public function logout(){
        Session::set("admin", []);
        $this->keeplogin(0);
        $this->success('退出登陆成功成功', ['keeptime'=>0], 1);
    }
}
